local require = require
local ngx_re_find = ngx.re.find
local lrucache = require "resty.lrucache"
local resolver = require "resty.dns.resolver"
local cache_storage = lrucache.new(200)-----创建本地缓存
----判断是否是ip地址
local _is_addr = function(hostname)
    return ngx_re_find(hostname, [[\d+?\.\d+?\.\d+?\.\d+$]], "jo")
end

if ngx.shared.DNS:get(1)==nil then
    ngx.log(ngx.INFO,"-----ngx.shared.DNS.get(0) 为空 ")
else
    ngx.log(ngx.INFO,"-----打印 ngx.shared.DNS.get(0) "..(ngx.shared.DNS:get(1)))
end

local _get_addr = function(hostname)
    if _is_addr(hostname) then
        return hostname, hostname
    end

    ngx.log(ngx.INFO,"-----判断是域名 就从缓存中获取看看")
    -----如果不是ip地址 就从缓存中获取看看
    local addr = cache_storage:get(hostname)
    ngx.log(ngx.INFO,"----- -----获取到了就返回")
    -----获取到了就返回
    if addr then
        ngx.log(ngx.INFO,"----- -----获取到了直接返回")
        return addr, hostname
    end
    -----没有从本地的dns解析获取到 就从外部的dns服务器上去获取看看
    local r, err = resolver:new({
        nameservers = {ngx.shared.DNS:get(1)},
        retrans = 5,  -- 5 retransmissions on receive timeout
        timeout = 2000,  -- 2 sec
    })

    if not r then
        return nil, hostname
    end
    -------开始dns 查询
    local answers, err = r:query(hostname, {qtype = r.TYPE_A})
    -------如果没有查到返回为空
    if not answers or answers.errcode then
        return nil, hostname
    end
    --如果查到了 解析里面的ip地址值
    for i, ans in ipairs(answers) do
        if ans.address then
            cache_storage:set(hostname, ans.address, 300)
            ------缓存住然后返回结果
            return ans.address, hostname
        end
    end

    return nil, hostname
end

ngx.say(_get_addr("www.baidu.com"))
ngx.say(_get_addr("192.168.0.1"))

